﻿package me.zhengjie.common.base

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.bean.copier.CopyOptions
import com.fasterxml.jackson.annotation.JsonTypeName
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.persistence.Column
import jakarta.persistence.EntityListeners
import jakarta.persistence.MappedSuperclass
import me.zhengjie.common.utils.JacksonUtil
import org.apache.commons.lang3.builder.ToStringBuilder
import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.UpdateTimestamp
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.LastModifiedBy
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.sql.Timestamp


/**
 * @author Kuki
 * @Date 2024/11/10 1:59:04
 */

@MappedSuperclass
@JsonTypeName("BaseEntity")
@EntityListeners(AuditingEntityListener::class)
 open class BaseEntity (
    @CreatedBy @Column(name = "create_by", updatable = false)
    @Schema(name = "创建人", hidden = true)
    var createBy: String? = null,

    @LastModifiedBy
    @Column(name = "update_by")
    @Schema(name = "更新人", hidden = true)
    var updateBy: String? = null,

    @Column(name = "create_time")
    @Schema(name = "创建时间", hidden = true)
    @CreationTimestamp
    var createTime: Timestamp? = null,

    @Column(name = "update_time")
    @Schema(name = "更新时间", hidden = true)
    @UpdateTimestamp
    var updateTime: Timestamp? = null
){
    annotation class Update

    companion object {
        fun fromJson(json: String): BaseEntity? {
            val obj=JacksonUtil.parseObject(json, BaseEntity::class.java)!!
            return when(obj){
                is BaseEntity-> obj
                else -> null
            }
        }
    }

    fun tojson():String? {
        return JacksonUtil.toJSONString(this)
    }

    fun copy(source: BaseEntity?) {
        BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true))
    }
}
